from google.appengine.ext import db
from google.appengine.api import users

class CacheDB(db.Model):
    '''Cache model.'''
    user = db.UserProperty(required=True)
    ckey = db.StringProperty(required=True)
    data = db.TextProperty()
    addition = db.TextProperty()

class Cache(object):
    '''Provide cache system.'''

    def __init__(self):
        pass

    def get(self, ckey):
        '''Return data from db that match `ckey`.'''

        user = users.get_current_user()
        return CacheDB.gql("WHERE user =  :1 AND ckey = :2", user, ckey).get()

    def set(self, ckey, data, addition=''):
        '''Save data to db'''

        g = self.get(ckey)
        if g:
            g.data = data
            if addition:
                g.addition = addition
        else:
            user = users.get_current_user()
            g = CacheDB(user = user, ckey = ckey, data = data, addition=addition)

        g.put()         
    
    def clear(self):
        '''Clear cache data.'''

        r = CacheDB.gql("WHERE user = :1", users.get_current_user())
        for e in r:
            e.delete() 
